package com.qf.tenement.tenement_user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.tenement.tenement_entity.ResultData;
import com.qf.tenement.tenement_entity.User;
import com.qf.tenement.tenement_user.dao.UserDao;
import com.qf.tenement.tenement_user.service.UserService;
import com.qf.tenement.tenement_utils.MD5Utils;
import com.qf.tenement.tenement_utils.MessageCodeConstants;
import com.qf.tenement.tenement_utils.TokenUtil;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public ResultData save(User user) {
        //随机生成一个盐
        final String substring = UUID.randomUUID().toString().substring(3, 8);
        user.setSalt(substring);
        //分配给用户一个编号
        user.setCode("10001");
        user.setStatus(1);
        //密码加盐md5
        String md5 = MD5Utils.md5(user.getPassword() + substring);
        user.setPassword(md5);
        final int i = userDao.insert(user);
        if (i > 0){
            return ResultData.createSuccessJsonResult(null);
        }
        return ResultData.createFailJsonResult(MessageCodeConstants.REGISTER_FAIL,"注册失败");
    }

    @Override
    public ResultData login(User user) {
        final QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("u_name",user.getName());
        User user1 = userDao.selectOne(wrapper);
        System.out.println(user1);
        if (user1 == null){
            return ResultData.createFailJsonResult(MessageCodeConstants.LOGIN_FAIL,"用户或密码错误");
        }else {
            String md5 = MD5Utils.md5(user.getPassword() + user1.getSalt());
            if (md5.equals(user1.getPassword())){
                // 登录成功需要生成jwt
                // 将用户信息转换成json格式 生成token
                user1.setPassword(null);
                ObjectMapper mapper = new ObjectMapper();
                String s = null;
                try {
                    s = mapper.writeValueAsString(user1);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                String token = TokenUtil.createToken(s);
                // 将用户Email写入redis 设置一个超时时间
                String email = user1.getEmail();
                BoundValueOperations ops = redisTemplate.boundValueOps(email);
                ops.set("time", Duration.ofMinutes(30));
                return ResultData.createSuccessJsonResult(token);
            }else {
                return ResultData.createFailJsonResult(MessageCodeConstants.LOGIN_FAIL,"用户名或密码错误");
            }
        }
    }

    @Override
    public ResultData check(String token) {
        System.out.println(token);
        // 验证token
        ResultData data = TokenUtil.verifyJWT(token);
        if (data.getCode().equals("10000")) {
            // 验证是否超时
            // 得到当前用户信息
            String jsonstring = (String)data.getData();
            System.out.println(token);
            ObjectMapper mapper = new ObjectMapper();
            try {
                User user = mapper.readValue(jsonstring, User.class);
                String email = user.getEmail();
                BoundValueOperations ops = redisTemplate.boundValueOps(email);
                if (ops.get() == null){
                    return ResultData.createFailJsonResult(MessageCodeConstants.LOGIN_TIME_OUT,"登录超时，请重新登录");
                }else {
                    ops.set("time",Duration.ofMinutes(30));
                }
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return ResultData.createFailJsonResult(MessageCodeConstants.LOGIN_TIME_OUT,"登录超时，请重新登录");
            }

        }else {
            return data;
        }
        return data;
    }





















}
